#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created: 11/18/2008
# $Id$
# Copyright (c) 2008,2009 by University College London
# Authors:
# Didrik Pinte <dpinte@dipole-consulting.com>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.
'''
HydroPlatform application module. 

This is a simple overload of the ThubanApplication class
'''
import sys
import os
import traceback
import wx
print sys.path

from Thuban.UI import application, mainwindow
from Thuban.UI.dock import DockFrame
from Thuban import _

from hydroplatform.ui.about import About
from hydroplatform.ui.resources import get_bitmap_resource
from hydroplatform.ui import exceptiondialog
from hydroplatform.ui.menu import NodeTypeMenu, set_hydroplatform_menu
from hydroplatform.ui import session


__revision__ = '$Revision$'

BASE = os.path.dirname(os.path.abspath(__file__))


class HydroPlatformApplication(application.ThubanApplication):
    '''
    HydroPlatform main application class
    '''
    
    def splash_screen(self):
        '''
        Define a custom splash screen for this application
        '''
        bmp   = get_bitmap_resource('logo', wx.BITMAP_TYPE_JPEG)
        # appears during 5 seconds
        wx.SplashScreen(bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
                        5000, None, -1)

    def read_startup_files(self):
        '''
        Overload default read_startup_files method in order to load the
        hydroplatoform modules
        '''
        #import hydroplatform.ui.thubanmod
        application.ThubanApplication.read_startup_files(self)
        
        
    def CreateMainWindow(self):
        """Create and return the main window for the application.

        Overriden from ThubanApplication class
        main window.
        """
        msg = (_("This is the wxPython-based Graphical User Interface"
               " for exploring geographic data"))
        
        def update_title(self, text=None):
            '''
            Update the map title using the givent text and the map name
            '''
            mymap = self.Map()
            title = "HydroPlatform"
            if text is not None:
                title = "%s - %s" % (title, text)
            if mymap is not None:
                title = _("%s - %s") % (title, mymap.Title())
            self.SetTitle(title)
            
        def on_close(self, event):
            '''
            Closes the db session
            
            FIXME : should manage the potential changes that have no been 
            committed
            '''
            if hasattr(self.application.session, "dbsession") and  \
               self.application.session.dbsession is not None:
                self.application.session.dbsession.close()
                
            # FIXME: it would be better to tie the unsubscription to
            # wx's destroy event, but that isn't implemented for wxGTK
            # yet.
            for channel in self.update_status_bar_messages:
                self.canvas.Unsubscribe(channel, self.update_status_bar)

            DockFrame.OnClose(self, event)
            for dlg in self.dialogs.values():
                dlg.Destroy()
            self.canvas.Destroy()
            self.Destroy()
            
        def about(self):
            dlg = About(self)
            dlg.ShowModal()
            dlg.Destroy()

        
        mainwindow.MainWindow.update_title = update_title
        mainwindow.MainWindow.OnClose = on_close
        mainwindow.MainWindow.About = about
        set_hydroplatform_menu()
        return  mainwindow.MainWindow(None, -1, "Thuban", self, None,
                                     initial_message = msg,
                                     size = (600, 400))
        
        
        
    def ShowExceptionDialog(self, exc_type, exc_value, exc_traceback):
        """Overloading default ThubanApplication exception dialog
        
        Show a message box with information about an exception.
    
        The parameters are the usual values describing an exception in
        Python, the exception type, the value and the traceback.
    
        This method can be used as a value for the sys.excepthook.
        """

        if self.in_exception_dialog:
            return
        self.in_exception_dialog = 1
        while wx.IsBusy():
            wx.EndBusyCursor() # reset the mouse cursor

        try:
            lines = traceback.format_exception(exc_type, exc_value,
                                            exc_traceback)
            message = _("An unhandled exception occurred:\n%s\n"
                        "(please report to"
                    " http://svn.dipole-consulting.com/hydroplatform/trac.cgi)"
                        "\n\n%s") % (exc_value, "".join(lines))
            print message

            # We don't use an explicit parent here because this method might
            # be called in circumstances where the main window doesn't exist
            # anymore.
            exceptiondialog.run_exception_dialog(None, message)

        finally:
            self.in_exception_dialog = 0
            # delete the last exception info that python keeps in
            # sys.last_* because especially last_traceback keeps
            # indirect references to all objects bound to local
            # variables and this might prevent some object from being
            # collected early enough.
            sys.last_type = sys.last_value = sys.last_traceback = None
 
            
    def get_nodetype_menu(self, context):
        '''
        Facility function to get the nodetype menu
        '''
        if not hasattr(self, "nodetypemenu"):
            self.nodetypemenu = NodeTypeMenu(context) 
        return self.nodetypemenu
